import { Component, OnDestroy, OnInit } from '@angular/core';
import { AddVMSService } from '../add-vms.service';
import { ToolsService } from 'app/shared/service';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { TranslateService } from '@ngx-translate/core';
import { parse } from 'date-fns';
import { Subscription } from 'rxjs';

@Component({
    selector: 'itmp-add-vms-info',
    templateUrl: './vms-message-info.component.html',
    styleUrls: ['./vms-message-info.component.css']
})
export class VmsMessageInfoComponent implements OnInit, OnDestroy {
    categoryId: any; // 消息类型名
    messageName: any; // 图库名称
    selectedValue = {
        messageCategory: null
    };
    selectionList = {
        messageCategory: ['Accident(main carriageway)']
    };
    containerStyle = {
        width: '320px',
        height: '32px'
    };
    title = null;
    pageUndo: any = []; // 撤销
    pageRedo: any = []; // 恢复
    contentCss: string;
    editTextSeq = null;
    text: null;
    contentStyleList: any;
    allList = {
        fontSize: [
            { value: 12, name: '12font', style: '12px' },
            { value: 13, name: '13font', style: '13px' },
            { value: 14, name: '14font', style: '14px' },
            { value: 15, name: '15font', style: '15px' },
            { value: 16, name: '16font', style: '16px' },
            { value: 24, name: '24font', style: '32px' },
            { value: 32, name: '32font', style: '48px' },
            { value: 48, name: '48font', style: '64px' }
        ],
        fontWeight: [{ value: 'bold', name: 'bold', style: 'bold' }, { value: 'normal', name: 'normal', style: 'normal' }],
        color: [
            { value: 1, name: 'white', style: '#ffffff' },
            { value: 2, name: 'green', style: '#00ff01' },
            { value: 3, name: 'red', style: '#fe0000' },
            { value: 4, name: 'yellow', style: '#ffff01' },
            { value: 5, name: 'blue', style: '#0000fe' },
            { value: 6, name: 'bluish green', style: '#01ffff' },
            { value: 7, name: 'purple', style: '#ff00fe' }
        ],
        lettSpacing: [
            { value: 1, name: '1spacing', style: '1px' },
            { value: 2, name: '2spacing', style: '2px' },
            { value: 3, name: '3spacing', style: '3px' },
            { value: 4, name: '4spacing', style: '4px' },
            { value: 5, name: '5spacing', style: '4px' },
            { value: 6, name: '6spacing', style: '4px' }
        ],
        fontName: [
            { value: 'Arial', name: 'Arial', style: 'Arial' },
            { value: 'Thin Medium', name: 'Thin Medium', style: 'Thin Medium' },
            { value: 'Sans-serif', name: 'Sans-serif', style: 'Sans-serif' },
            { value: 'Palatino', name: 'Palatino', style: 'Palatino' },
            { value: 'MS Gothic', name: 'MS Gothic', style: 'MS Gothic' },
            { value: 'serif', name: 'serif', style: 'serif' },
            { value: 'Optima', name: 'Optima', style: 'Optima' },
            { value: 'Fira Code', name: 'Fira Code', style: 'Fira Code' },
            { value: 'Menlo', name: 'Menlo', style: 'Menlo' },

            { value: 'RastaManOblique', name: 'RastaManOblique', style: 'RastaManOblique' },
            { value: 'PROXON', name: 'PROXON', style: 'PROXON' },
            { value: `Mono Regular`, name: `Mono Regular`, style: `Mono Regular` },
            { value: 'ARROSE', name: 'ARROSE', style: 'ARROSE' },
            { value: 'M PLUS 1 Code', name: 'M PLUS 1 Code', style: `'M PLUS 1 Code'` },
            { value: 'M PLUS Code Latin', name: 'M PLUS Code Latin', style: 'M PLUS Code Latin' },
            { value: 'Gowun Dodum', name: 'Gowun Dodum', style: 'Gowun Dodum' },
            { value: 'Hahmlet', name: 'Hahmlet', style: 'Hahmlet' },
            { value: 'Lexend Tera', name: 'Lexend Tera', style: 'Lexend Tera' },
            { value: 'Chakra Petch', name: 'Chakra Petch', style: 'Chakra Petch' },

            { value: 'Bungee', name: 'Bungee', style: 'Bungee' },
            { value: 'LED Counter 7', name: 'LED Counter 7', style: `'LED Counter 7'` },
            { value: '5by7', name: '5by7', style: '5by7' },
            { value: 'Matrix Complex 3D NC', name: 'Matrix Complex 3D NC', style: `'Matrix Complex 3D NC'` },
            { value: 'Matrix Complex Wave NC', name: 'Matrix Complex Wave NC', style: 'Matrix Complex Wave NC' },
            { value: 'Matrix Complex NC', name: 'Matrix Complex NC', style: 'Matrix Complex NC' },
            { value: 'Dot Spot', name: 'Dot Spot', style: 'Dot Spot' },
            { value: 'Ring Matrix 3D', name: 'Ring Matrix 3D', style: `'Ring Matrix 3D'` },
            { value: 'Ring Matrix', name: 'Ring Matrix', style: 'Ring Matrix' },
            { value: 'Ring Matrix Two', name: 'Ring Matrix Two', style: 'Ring Matrix Two' },

            { value: 'High speed', name: 'High speed', style: 'High speed' },
            { value: 'Greaseballs', name: 'Greaseballs', style: 'Greaseballs' },
            { value: 'Double Strike', name: 'Double Strike', style: 'Double Strike' },
            { value: '5x5 Dots', name: '5x5 Dots', style: `'5x5 Dots'` },
            { value: 'D3 Electronism', name: 'D3 Electronism', style: `'D3 Electronism'` },
            { value: 'DotMatrix', name: 'DotMatrix', style: 'DotMatrix' }
        ]
    };
    fontFamilyModel = 'Arial';
    fontWeightModel = 'normal';
    deafultMsg = 'Input Text Hear...';
    subscription: Subscription = null;

    constructor(public addService: AddVMSService, private toolsService: ToolsService, private translateService: TranslateService) {}

    ngOnInit() {
        this.subscription = this.addService.getDisplayMessage().subscribe(res => {
            this.setContentStyleList();
        });
        this.setContentStyleList();
        // this.containerStyle = this.addService.displayMessage.deviceConfig;
        this.init();
        // this.setCategory();
        this.initcdkDropListConnect();
        this.translate('DisseminationManagement.MessageLibrary.Input_Text_Hear').subscribe(value => {
            this.deafultMsg = value;
        });
    }

    ngOnDestroy(): void {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }

    setContentStyleList() {
        const { displayMessage } = this.addService;
        this.contentStyleList = [];
        this.categoryId = displayMessage.category.categoryId;
        this.messageName = displayMessage.msgName;
        displayMessage.templatePages.forEach((pages, index) => {
            this.contentStyleList.push([]);
            const cWidth = displayMessage.deviceInfo.width;
            const cHeight = displayMessage.deviceInfo.height;
            /*if (pages.templateGraphics) {
                pages.templateGraphics.forEach((value, i) => {
                    textWidth = displayMessage.deviceInfo.width - value.graphicAreaW;
                    textHeight = displayMessage.deviceInfo.height - value.graphicAreaH;
                });
            }*/
            if (pages.templateTexts && pages.templateTexts.length) {
                const textAreaY = pages.templateTexts[0].textAreaY;
                const textHeight = (cHeight - textAreaY - 2) / pages.templateTexts.length;
                pages.templateTexts.forEach((item, idx) => {
                    let params;
                    const data = pages.texts[idx];
                    const lang = localStorage.getItem('itmp_lang');
                    if (data) {
                        params = {
                            // text: data.text || this.deafultMsg,
                            text:
                                lang === 'en' ? data.text || 'Text...' : lang === 'zh' ? data.text || '文本...' : data.text || 'Bản văn...',
                            style: {
                                // 'font-size': '16px',
                                'font-size': data.font,
                                // 'font-family': data.fontName ? data.fontName === 'NA' ? 'Arial' : data.fontName : 'Arial',
                                color: data.foreColor,
                                // color: 'white',
                                'letter-spacing': data.charSpacing,
                                left: data.textAreaX + 'px',
                                top: data.textAreaY + 'px',
                                // width: item.width + 'px',
                                // height: item.height + 'px'
                                width: cWidth - data.textAreaX - 2 + 'px',
                                height: textHeight + 'px',
                                padding: 0
                            },
                            limit: {
                                maxChars: item.maxChars
                            }
                        };
                    } else {
                        params = {
                            // text: this.deafultMsg,
                            text: lang === 'en' ? 'Text...' : lang === 'zh' ? '文本...' : 'Bản văn...',
                            // text: 'Text...',
                            style: {
                                'font-size': item.font + 'px',
                                // 'font-family': item.fontName ? item.fontName === 'NA' ? 'Arial' : item.fontName : 'Arial',
                                // 'font-size': '16px',
                                // color: 'white',
                                color: this.allList['color'][0].style,
                                // color: this.allList['color'][item.foreColor] && this.allList['color'][item.foreColor].style,
                                'letter-spacing': this.allList['lettSpacing'][item.charSpacing].style,
                                left: item.textAreaX + 'px',
                                top: item.textAreaY + 'px',
                                // width: item.width + 'px',
                                // height: item.height + 'px'
                                width: cWidth - item.textAreaX - 2 + 'px',
                                height: textHeight + 'px',
                                padding: 0
                            },
                            limit: {
                                maxChars: item.maxChars
                            }
                        };
                    }
                    this.contentStyleList[index].push(params);
                });
            }
        });
        this.containerStyle = {
            width: displayMessage.deviceInfo.width + 'px',
            height: displayMessage.deviceInfo.height + 'px'
        };
    }

    translate(text) {
        return this.translateService.get(text);
    }

    // 当输入内容超出文本框时，禁止继续输入
    onSearch() {
        $('#vmsDescription').on('input', function(e) {
            const t = e.target;
            const realHeight = document.getElementById('vmsDescription').scrollHeight;
            const clientHeight = document.getElementById('vmsDescription').clientHeight;
            document.getElementById('vmsDescription').scrollTop = realHeight;
            if (realHeight > clientHeight) {
                t['value'] = t['value'].substring(0, t['value'].length - 1);
            }
        });
    }

    // 拖拽关联的id获取
    initcdkDropListConnect() {
        this.addService.cdkDropListConnectId = [];
        // this.addService.displayMessage.templatePages[this.addService.showPage].templateGraphics.forEach((item, index) => {
        //     this.addService.cdkDropListConnectId.push('vmsInfoContainer' + index);
        // });
        for (let i = 0; i < 10; i++) {
            this.addService.cdkDropListConnectId.push('vmsInfoContainer' + i);
        }
    }

    init() {
        this.contentCss = this.addService.displayMessage.templatePages[0].align || 'flex-start';
        this.pageUndo = [];
        this.pageRedo = [];
    }

    // 对齐方式
    align(flag, param, width) {
        this.pageUndo.push({
            type: 'style',
            page: this.addService.showPage,
            val: this.contentCss
        });
        if (flag === 'flex-start') {
            param.forEach(item => {
                item.style['text-align'] = 'left';
            });
        } else if (flag === 'center') {
            param.forEach(item => {
                item.style['text-align'] = 'center';
            });
        } else {
            param.forEach(item => {
                item.style['text-align'] = 'right';
            });
        }
        this.contentCss = flag;
    }

    // 储存改变前的数据
    changeData(flag) {
        this.pageUndo.push({
            type: 'data',
            page: this.addService.showPage,
            val: flag
        });
        // this.addService.setDisplayMessage(this.addService.showPage, flag);
    }

    goToPage(page) {
        this.addService.setShowPage(page);
        const temp = this.addService.displayMessage.templatePages[page].text;
        this.title = temp ? temp.text : null;
    }

    // 撤销
    undo() {
        if (this.pageUndo.length < 1) {
            return;
        }
        this.pageRedo.push({
            ...this.pageUndo[this.pageUndo.length - 1]
        });
        this.addService.showPage = this.pageUndo[this.pageUndo.length - 1].page;
        if (this.pageUndo[this.pageUndo.length - 1].type === 'style') {
            this.contentCss = this.pageUndo[this.pageUndo.length - 1].val;
        } else {
            this.addService.updateTemplatePages(this.addService.showPage, this.pageUndo[this.pageUndo.length - 1].val);
        }
        this.pageUndo.splice(this.pageUndo.length - 1, 1);
    }

    // 恢复
    redo() {
        if (this.pageRedo.length < 1) {
            return;
        }
        this.pageUndo.push({
            ...this.pageRedo[this.pageRedo.length - 1]
        });
        this.addService.showPage = this.pageRedo[this.pageRedo.length - 1].page;
        if (this.pageRedo[this.pageRedo.length - 1].type === 'style') {
            this.contentCss = this.pageRedo[this.pageRedo.length - 1].val;
        } else {
            this.addService.updateTemplatePages(this.addService.showPage, this.pageRedo[this.pageRedo.length - 1].val);
        }
        this.pageRedo.splice(this.pageRedo.length - 1, 1);
    }

    // 拖放
    drop(event: CdkDragDrop<string[]>) {
        this.changeData(this.toolsService.isClone(this.addService.displayMessage.templatePages[this.addService.showPage]));
        const page = this.addService.displayMessage.templatePages[this.addService.showPage];
        if (event.previousContainer.id === 'graphicsContainer') {
            const index = event.container.id[16];
            page.graphics[index] = {
                messageId: null,
                graphicSeq: this.addService.showPage + 1,
                vmsGraphic: this.addService.selectGraphics
            };
            // this.addService.updateTemplatePages(this.addService.showPage, page);
        } else {
            const curIndex = event.container.id[16];
            const preIndex = event.previousContainer.id[16];
            const temp = page.graphics[curIndex];
            page.graphics[curIndex] = page.graphics[preIndex];
            page.graphics[preIndex] = temp;
        }
    }

    // 新增标签页
    // addPage() {
    //     const displayMessageItem = {
    //         graphicSeq: null, // 播放顺序
    //         pageSeq: null,
    //         graphics: [],
    //         text: {
    //             text: null,
    //             textimageUrl: null
    //         }
    //     };
    //     this.addService.addTemplatePages(displayMessageItem);
    //     this.goToPage(this.addService.displayMessage.templatePages.length - 1);
    //     this.pageUndo.push([]);
    //     this.pageRedo.push([]);
    // }
    setTitle() {
        // const temp = this.addService.displayMessage.templatePages[this.addService.showPage];
        // temp.text.text = this.title;
        // this.addService.updateTemplatePages(this.addService.showPage, temp);
    }

    setCategory() {
        this.addService.selectionList.messageCategory.forEach(item => {
            if (item.categoryId === this.categoryId) {
                this.addService.displayMessage.category.categoryId = item.categoryId;
                this.addService.displayMessage.msgName = item.categoryName;
                this.categoryId = this.addService.displayMessage.category.categoryId;
                this.messageName = this.addService.displayMessage.msgName;
            }
        });
    }

    // text编辑
    startEdit(id, event, first, second) {
        if (
            this.contentStyleList[first][second].text === 'Text...' ||
            this.contentStyleList[first][second].text === '文本...' ||
            this.contentStyleList[first][second].text === 'Bản văn...'
        ) {
            this.contentStyleList[first][second].text = '';
        }
        // this.contentStyleList[text].text = ''
        event.preventDefault();
        event.stopPropagation();
        const theText = this.addService.displayMessage.templatePages[this.addService.showPage].texts[id];
        this.text = theText ? theText.text : '';
        this.editTextSeq = id;
    }

    test(e) {
        e = '';
    }

    // 保存文本编辑
    saveText(seq, e) {
        e.preventDefault();
        e.stopPropagation();
        if (seq === -1 || e.keyCode === 13) {
            // const theText = this.addService.displayMessage.templatePages[this.addService.showPage].texts[id];
            // if (theText) {
            //     theText.text = this.text === '' ? null : this.text;
            // } else {
            this.addService.displayMessage.templatePages[this.addService.showPage].texts[this.editTextSeq] = {
                text: this.text === '' ? null : this.text
            };
            // }
            this.editTextSeq = null;
        }
    }

    stopPropagation(event) {
        event.preventDefault();
        event.stopPropagation();
    }
}
